package com.ecgsystem.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.Toast;

import com.ecgsystem.connection.Connection;
import com.ecgsystem.constants.Commons;
import com.ecgsystem.constants.Constants;
import com.ecgsystem.R;

/**
 * TODO Put here a description of what this class does.
 * 
 * @author ANHTUAN. Created Sep 24, 2012.
 */
public class MainActivity extends Activity implements Runnable, Constants {
	/** Called when the activity is first created. */
	public static Connection conn;

	public static TabHost tabHost;

	private Thread thread;
	private EditText usernameEd;
	private EditText passwordEd;
	private CheckBox rem;
	private ProgressDialog dialogWait;
	private int loginResult;
	private Bundle patientList;
	private Intent i;

	String username;
	String password;

	boolean rememberlogin = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		Commons.HEIGHT = metrics.heightPixels;
		Commons.WIDTH = metrics.widthPixels;
		
		if(Commons.HEIGHT < Commons.WIDTH){
			int temp= Commons.HEIGHT;
			Commons.HEIGHT = Commons.WIDTH;
			Commons.WIDTH = temp;
		}

		Log.d("Height", Commons.HEIGHT + "   Width" + Commons.WIDTH);

		SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
		// chưa lưu thông tin server
		if (!pref.contains(PREFS_SERVER)) {
			saveServerDetails();
		}else{
			Commons.UDP_SERVER_ADDRESS = pref.getString(PREFS_SERVER, Commons.UDP_SERVER_ADDRESS);
			Commons.TCP_PORT = pref.getInt(PREFS_TCPPORT, Commons.TCP_PORT);
			Commons.UDP_PORT = pref.getInt(PREFS_UDPPORT, Commons.UDP_PORT);
		}

		username = pref.getString(PREF_USERNAME, null);
		password = pref.getString(PREF_PASSWORD, null);

		conn = new Connection();
		this.usernameEd = (EditText) findViewById(R.id.editText_username);
		this.passwordEd = (EditText) findViewById(R.id.editText_password);

		this.patientList = new Bundle();

		this.i = new Intent(MainActivity.this, PatientList.class);
		this.i.putExtras(this.patientList);

		rem = (CheckBox) findViewById(R.id.checkBox_remmember);

		if (username == null || password == null) {

		} else {
			this.usernameEd.setText(username);
			this.passwordEd.setText(password);
			this.rem.setChecked(true);
			this.thread = new Thread(MainActivity.this);
			showWaitDialog();
			this.thread.start();
		}

		final Button loginButton = (Button) findViewById(R.id.button_login);
		loginButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				rememberlogin = rem.isChecked();
				MainActivity.this.thread = new Thread(MainActivity.this);
				showWaitDialog();
				MainActivity.this.thread.start();
			}
		});
	}

	public void run() {
		username = this.usernameEd.getText().toString();
		password = this.passwordEd.getText().toString();
		this.loginResult = conn.login(username, password);
		this.handler.sendEmptyMessage(0);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (MainActivity.this.loginResult == OK) {
				if (rememberlogin == true) {
					saveLoginDetails();
				} else {
					removeLoginDetails();
				}
				startActivity(MainActivity.this.i);
				finish();
			} else if (MainActivity.this.loginResult == WRONG_PASSWD) {
				Toast.makeText(getApplicationContext(),
						"Tên đăng nhập/mật khẩu không đúng", Toast.LENGTH_SHORT)
						.show();
				MainActivity.this.usernameEd.setText("");
				MainActivity.this.passwordEd.setText("");
				MainActivity.this.usernameEd.clearFocus();
			} else if (MainActivity.this.loginResult == CONNECTION_ERR) {
				Toast.makeText(getApplicationContext(),
						"Lỗi kết nối tới Server", Toast.LENGTH_SHORT).show();
			}
			
			deleteWaitDialog();
		}
	};

	private void showWaitDialog() {
		this.dialogWait = ProgressDialog.show(this, "",
				"Signing to ECG System...", true, false);
	}

	private void deleteWaitDialog() {
		if (this.dialogWait != null) {
			this.dialogWait.dismiss();
		}
	}

	private void saveLoginDetails() {
		getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
				.putString(PREF_USERNAME, username)
				.putString(PREF_PASSWORD, password).commit();
	}

	private void saveServerDetails() {
		getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
				.putString(PREFS_SERVER, Commons.UDP_SERVER_ADDRESS)
				.putInt(PREFS_TCPPORT, Commons.TCP_PORT)
				.putInt(PREFS_UDPPORT, Commons.UDP_PORT).commit();
	}

	public void removeLoginDetails() {
		getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
				.remove(PREF_USERNAME).remove(PREF_PASSWORD).commit();

	}
	
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case R.id.menu_logout:
			Toast.makeText(MainActivity.this, "Logout", Toast.LENGTH_SHORT).show();
			
			//logout
			getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
			.remove(PREF_USERNAME).remove(PREF_PASSWORD).commit();
			
			System.exit(0);
			return true;
		case R.id.menu_conf:
			Bundle bundleConf = new Bundle();
			Intent intent = new Intent(MainActivity.this, Configuration.class);
			intent.putExtras(bundleConf);
			startActivity(intent);
			return false;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}